<script lang="jsx" setup>
import { ref, watch } from 'vue';
import { CloseCircleOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { Button } from 'ant-design-vue';
import SortFieldSelector from './sort-field-selector.vue';
import SortModeSelector from './sort-mode-selector.vue';
import { assignStatusOptions } from '@/util/const.js';
import { REQU, SignInInfoInvalidCondPair, useResp } from '@/net/requ.js';
const props = defineProps(['visible', 'tasks']);
const emit = defineEmits(['update:visible', 'ok']);

const orderFieldList = ref([
  { value: 'update_by_time', label: '最新' },
  { value: 'created_by_time', label: '最早' },
  { value: 'task_name', label: '名称' }
]);

const loading = ref(false);
const list = ref([]);

const params = ref({
  group: '',
  type: '',
  assignmentStatus: '' /* toDic(['label', 'value'], assignStatusOptions)['已完成'] */,
  date: null,
  get startTime() {
    return this.date?.[0]?.format('YYYY-MM-DD') ?? '';
  },
  get endTime() {
    return this.date?.[1]?.format('YYYY-MM-DD') ?? '';
  },
  start: 1,
  limit: 10,
  queryString: '',
  orderField: orderFieldList.value[0].value,
  orderType: 'DESC',
});

watch(
  () => params.value.queryString,
  () => (params.value.start = 1)
);

watch(params, getTasks, { deep: true });

const columns = ref([
  {
    title: '任务',
    dataIndex: 'taskName',
  },
  {
    align: 'center',
    width: 90,
    title: '操作',
    customRender: ({ record }) => (
      <Button
        type="link"
        onClick={() => tasks.value.find(item => item.id == record.id) || tasks.value.push(record)}>
        选择
      </Button>
    ),
  },
]);

const pagination = ref({
  total: 0,
  get current() {
    return params.value.start;
  },
  get pageSize() {
    return params.value.limit;
  },
  onChange: page => {
    params.value.start = page;
  },
  position: ['bottomCenter'],
});

function getTasks() {
  loading.value = true;
  REQU(`/api/task/list?${ new URLSearchParams(params.value) }`)
  .then(useResp({
    succ: result => {
      list.value = result.data.list;
      pagination.value.total = result.data.total;
    },
    fail: R.cond([SignInInfoInvalidCondPair()]),
  }))
  .finally(() => loading.value = false);
}

const tasks = ref(R.clone(props.tasks));

function main() {
  getTasks();
}

main();

function onCalendarChange(...args) {
  console.log(args);
}
</script>

<template>
  <a-modal
    :visible="props.visible"
    centered
    :width="1200"
    title="选择任务"
    class="task-selector"
    @ok="() => {
      emit('ok', tasks);
      emit('update:visible', false);
    }"
    @cancel="() => emit('update:visible', false)">
    <div style="width: 580px;">
      <div class="filter" style="display: flex; gap: 16px; margin-bottom: 14px;">
        <a-input
          v-model:value="params.queryString"
          placeholder="输入关键字搜索任务"
          allow-clear
          style="width: 200px; border-radius: 18px;">
          <template #prefix>
            <search-outlined style="color: rgb(181,181,181);" />
          </template>
        </a-input>

        <div>
          <span>创建日期：</span>
          <a-range-picker
            v-model:value="params.date"
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
            @calendarChange="onCalendarChange"
          >
          </a-range-picker>
        </div>

        <div class="assign">
          <span>分配状态：</span>
          <a-select
            v-model:value="params.assignmentStatus"
            :options="[{ value: '', label: '全部' }].concat(assignStatusOptions)"
            style="width: 100px;"
          >
          </a-select>
        </div>

        <sort-mode-selector v-model:value="params.orderType"></sort-mode-selector>

        <sort-field-selector
          :list="orderFieldList"
          v-model:value="params.orderField"
        >
        </sort-field-selector>
      </div>

      <a-table
        size="small"
        :pagination="pagination"
        :columns="columns"
        :data-source="list"
      >
      </a-table>
    </div>
    
    <template v-if="0 < tasks.length">
      <ul>
        <template
          v-for="task in tasks"
          :key="task.id">
          <li>
            <span>{{ task.taskName }}</span>
            <a-button
              type="danger"
              ghost
              @click="() => tasks.splice(tasks.indexOf(task), 1)">
              <template #icon><close-circle-outlined /></template>
            </a-button>
          </li>
        </template>
      </ul>
    </template>
    <template v-else>
      <a-empty description="请选择实验"></a-empty>
    </template>
  </a-modal>
</template>

<style>
.task-selector .ant-modal-body {
  display: flex;
  gap: 14px;
}

.task-selector .filter {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 14px;
}

.task-selector .ant-modal-body > :nth-child(2) { flex: 1; }

.task-selector .ant-modal-body > .ant-empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.task-selector .ant-modal-body > ul > li {
  display: flex;
  gap: 1em;
  align-items: center;
  padding-top: .5em;
  padding-bottom: .5em;
  border-bottom: 1px solid rgb(228,228,228);
}

.task-selector .ant-modal-body > ul .ant-btn-danger {
  flex-shrink: 0;
  border: 0;
  box-shadow: none;
  margin-left: auto;
}
</style>
